import moment from 'moment';
import { message } from 'antd';
import {
  getDevInfo,
  setDevBright,
  setDevPower,
  addDevice,
  removeDevice,
  getDevBasicInfo,
  editDevice,
  setIpAddress,
  deviceTest,
  setDevReboot,
  setDevWIFI,
  getCompany,
  getProgInfo,
  expDevInfos,
  queryHwInfo,
  getCityCodes,
  SetOneKeyOpenScr,
  SetOneKeyCloseScr,
  SetOneKeyPubLish,
  SetOneKeyPubLishApply,
  setTimingSetBrightness,
  queryAlarm,
  setAlarm,
  fetchUserCodes,
  getOtaFile,
  getOtaMode,
  setOtaFile,
  setOtaUninstall,
} from '../services/api';

function method(str, a, b) {
  let type = 'string';
  if (str === 'createTime') {
    type = 'date';
  } else if (str === 'onOffline') {
    type = 'num';
  } else if (str === 'gpsStatus') {
    type = 'num';
  }

  switch (type) {
    case 'num': // 数字排序
      return a - b;
    case 'date': // 日期排序，IE8下'2012-12-12'这种格式无法设置时间，替换成'/'
      return moment(a).unix() - moment(b).unix();
    default:
      // 字符串排序
      if (a === null || a === undefined || a === '') {
        return 1;
      } else {
        return a.localeCompare(b);
      }
  }
}
export default {
  namespace: 'dev',

  state: {
    list: [],
    proglist: [],
    onDevNum: 0,
    devNum: 0,
    total: 0,
    pagination: {
      current: 1,
      pageSize: 10,
      pageSizeOptions: ['10', '20', '30', '40', '50', '80', '100'],
    },
    companyIdCodes: [],
    cityCodes: [],
    UserCodes: [],
    otaFile: [],
    otaMode: [],
  },

  effects: {
    *add({ payload, callback }, { call, put }) {
      // console.log('add device payload:', payload);
      const response = yield call(addDevice, payload);
      // yield put({
      //   type: 'save',
      //   payload: response,
      // });
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *oneKeyOpenScr({ payload, callback }, { call }) {
      const response = yield call(SetOneKeyOpenScr, payload);

      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *oneKeyPubLish({ payload, callback }, { call }) {
      const response = yield call(SetOneKeyPubLish, payload);

      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *oneKeyPubApply({ payload, callback }, { call }) {
      const response = yield call(SetOneKeyPubLishApply, payload);

      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },

    *oneKeyCloseScr({ payload, callback }, { call }) {
      const response = yield call(SetOneKeyCloseScr, payload);

      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },

    *edit({ payload, callback }, { call, put }) {
      // console.log('edit device payload:', payload);
      const response = yield call(editDevice, payload);
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const { devIds } = payload;
      const newpayload = { devIds: devIds.join(',') };
      const response = yield call(removeDevice, newpayload);
      if (response ?.result ?.code === 2001) {
        message.error('删除出错，请检查');
      } else {
        yield put({
          type: 'removeDevice',
          payload: { devIds },
        });
        if (callback) callback();
      }
    },
    *fetch({ payload }, { call, put }) {
      const response = yield call(getDevInfo, payload);
      // console.log('response', response);
      let dataSource = response.devInfos;
      if (payload) {
        if (payload.sorter) {
          const s = payload.sorter.split('_');

          if (s[1] === 'descend') {
            dataSource = dataSource.sort((prev, next) => method(s[0], next[s[0]], prev[s[0]]));
          } else {
            dataSource = dataSource.sort((prev, next) => method(s[0], prev[s[0]], next[s[0]]));
          }
          // dataSource = dataSource.sort((prev, next) => {
          //   if (s[1] === 'descend') {
          //     return next[s[0]] - prev[s[0]];
          //   }
          //   return prev[s[0]] - next[s[0]];
          // });
        }

        let pageSize = 10;
        if (payload.pageSize) {
          pageSize = payload.pageSize * 1;
        }

        const result = {
          list: dataSource,
          onDevNum: response.onDevNum,
          devNum: response.devNum,
          total: response.pageInfo.pageTotal,
          pagination: {
            total: response.pageInfo.pageTotal,
            pageSize,
            pageSizeOptions: ['10', '20', '30', '40', '50', '80', '100'],
            current: response.pageInfo.curPageNum || 1,
          },
        };
        yield put({
          type: 'save',
          payload: result,
        });
      } else {
        yield put({
          type: 'save',
          payload: {
            list: Array.isArray(response.devInfos) ? response.devInfos : [],
            onDevNum: response.onDevNum,
            total: response.pageInfo.pageTotal,
            pagination: {
              total: response.pageInfo.pageTotal,
              pageSize: 10,
              pageSizeOptions: ['10', '20', '30', '40', '50', '80', '100'],
              current: response.pageInfo.curPageNum,
            },
          },
        });
      }
    },
    *fetchprog({ payload }, { call, put }) {
      const response = yield call(getProgInfo, payload);
      // console.log('response', response);
      yield put({
        type: 'saveprog',
        payload: {
          list: Array.isArray(response.progNameCodes) ? response.progNameCodes : [],
        },
      });
    },
    *fetchOtaFile({ payload }, { call, put }) {
      const response = yield call(getOtaFile, payload);
      // console.log('response', response);
      yield put({
        type: 'saveOtaFile',
        payload: Array.isArray(response.devUpdateFileCodes) ? response.devUpdateFileCodes : [],
      });
    },
    *fetchOtaMode({ payload }, { call, put }) {
      const response = yield call(getOtaMode, payload);
      // console.log('response', response);
      yield put({
        type: 'saveOtaMode',
        payload: Array.isArray(response.otaFuncModCodes) ? response.otaFuncModCodes : [],

      });
    },
    *onExport({ payload, callback }, { call, put }) {
      const response = yield call(expDevInfos, payload);
      // console.log('response', response);
      if (response ?.expDevInfos ?.expFileUrl) callback(response.expDevInfos.expFileUrl);
    },
    *setBright({ payload, callback }, { call, put }) {
      const response = yield call(setDevBright, payload);
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *setOtaFile({ payload, callback }, { call, put }) {
      const response = yield call(setOtaFile, payload);
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *setUninstall({ payload, callback }, { call, put }) {
      const response = yield call(setOtaUninstall, payload);
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *queryAlarm({ payload, callback }, { call, put }) {
      const response = yield call(queryAlarm, payload);
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *setAlarm({ payload, callback }, { call, put }) {
      const response = yield call(setAlarm, payload);
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *setReboot({ payload, callback }, { call }) {
      const response = yield call(setDevReboot, payload);
      if (response ?.result ?.code === 2001) {
        message.error('重启失败，请检查');
      } else if (callback) callback();
    },
    *setWIFI({ payload, callback }, { call }) {
      const response = yield call(setDevWIFI, payload);
      if (response ?.result ?.code === 2001) {
        message.error('重启失败，请检查');
      } else if (callback) callback();
    },

    *setPower({ payload, callback }, { call }) {
      const response = yield call(setDevPower, payload);
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *queryHwInfo({ payload, callback }, { call }) {
      const response = yield call(queryHwInfo, payload);
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *setIpAddress({ payload, callback }, { call }) {
      const response = yield call(setIpAddress, payload);
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *deviceTest({ payload, callback }, { call }) {
      const response = yield call(deviceTest, payload);
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },

    *fetchBasicInfo({ payload }, { call, put }) {
      const response = yield call(getDevBasicInfo, payload);
      // console.log('response', response);
      yield put({
        type: 'basicInfo',
        payload: response.devBasicInfo,
      });
    },
    *fetchCompany({ payload }, { call, put }) {
      const response = yield call(getCompany, payload);
      // console.log('response', response);
      yield put({
        type: 'saveCompany',
        payload: response.companyIdCodes,
      });
    },
    *fetchCityCodes({ payload }, { call, put }) {
      const response = yield call(getCityCodes, payload);
      //console.log('response', response);
      yield put({
        type: 'saveCityCodes',
        payload: response.cityCodes,
      });
    },
    *fetchUserCodes({ payload }, { call, put }) {
      const response = yield call(fetchUserCodes, payload);
      //console.log('response', response);
      yield put({
        type: 'saveUserCodes',
        payload: response.authUserCodes,
      });
    },
    *timingSetBrightness({ payload, callback }, { call, put }) {
      const response = yield call(setTimingSetBrightness, payload);
      if (response ?.result ?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        onDevNum: action.payload.onDevNum,
        devNum: action.payload.devNum,
        total: action.payload.total,
        list: action.payload.list,
        pagination: action.payload.pagination,
      };
    },
    saveprog(state, action) {
      return {
        ...state,
        proglist: action.payload.list,
      };
    },
    removeRule(state, action) {
      const newlist = state.list.filter(item => action.payload.matId.indexOf(item.matId) === -1);
      return {
        ...state,
        list: newlist,
      };
    },
    removeDevice(state, action) {
      const newlist = state.list.filter(item => action.payload.devIds.indexOf(item.devId) === -1);
      return {
        ...state,
        list: newlist,
        pagination: action.payload.pagination,
      };
    },
    basicInfo(state, action) {
      return {
        ...state,
        devBasicInfo: action.payload,
      };
    },
    saveCompany(state, action) {
      return {
        ...state,
        companyIdCodes: action.payload,
      };
    },
    saveCityCodes(state, action) {
      return {
        ...state,
        cityCodes: action.payload,
      };
    },
    saveUserCodes(state, action) {
      return {
        ...state,
        UserCodes: action.payload,
      };
    },
    saveOtaFile(state, action) {
      return {
        ...state,
        otaFile: action.payload,
      };
    },
    saveOtaMode(state, action) {
      return {
        ...state,
        otaMode: action.payload,
      };
    },
  },
};
